package com.ywl.study.sharding.study06.config.precise;

import com.ywl.study.sharding.common.algorithm.PreciseModuloShardingTableAlgorithm;
import com.ywl.study.sharding.common.config.ExampleConfiguration;
import com.ywl.study.sharding.study03.util.DataSourceUtil;
import org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.StandardShardingStrategyConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 分表
 */
public class ShardingTablesConfigurationPrecise implements ExampleConfiguration {
    @Override
    public DataSource getDataSource() throws SQLException {
        ShardingRuleConfiguration configuration=new ShardingRuleConfiguration();
        configuration.getTableRuleConfigs().add(getOrderRuleConfiguration());
        configuration.getTableRuleConfigs().add(getOrderItemRuleConfiguration());
        configuration.getBindingTableGroups().add("t_order,t_order_item");
        configuration.getBroadcastTables().add("t_address");
        configuration.setDefaultTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("order_id",new PreciseModuloShardingTableAlgorithm()));
        return ShardingDataSourceFactory.createDataSource(createDataSource(),configuration,new Properties());
    }

    private static TableRuleConfiguration getOrderRuleConfiguration(){
        TableRuleConfiguration configuration=new TableRuleConfiguration("t_order","demo_ds.t_order_${[0,1]}");
        configuration.setKeyGeneratorConfig(new KeyGeneratorConfiguration("SNOWFLAKE","order_id",new Properties()));
        return configuration;
    }

    private static TableRuleConfiguration getOrderItemRuleConfiguration(){
        TableRuleConfiguration configuration=new TableRuleConfiguration("t_oder_item","demo_ds.t_order_item_${[0,1]}");
        configuration.setKeyGeneratorConfig(new KeyGeneratorConfiguration("SNOWFLAKE","order_item_id",new Properties()));
        return configuration;
    }


    private static Map<String,DataSource> createDataSource(){
        Map<String,DataSource> result=new HashMap<>();
        result.put("demo_ds", DataSourceUtil.createDataSource("demo_ds"));
        return result;
    }

    private static Properties getProperties() {
        Properties result = new Properties();
        result.setProperty("worker.id", "123");
        return result;
    }
}
